package controllers;

import java.util.ArrayList;
import java.util.List;

import models.Role;
import models.RoleMenu;
import models.Symenu;
import play.data.validation.Required;
import utils.YUtils;

/**
 * 角色菜单管理
 * @author masz 2012-12-15
 *
 */
public class RoleSymenus extends Application {

	public static void index(){
		List<Role> roles = Role.findAll();
		render(roles);
	}
	
	
	/**
	 * 树形下拉单
	 */
	public static void selectTreeMenu(Long roleId){
		Role r = Role.findById(roleId);
		String json = Symenu.selectedRoleMenu(Symenu.findParentPoint(),r)
				.replace("{\"Rows\":", "")
				.replaceAll("}$","");
		renderJSON(json);
	}
	
	public static void save(@Required Long roleId,@Required String menuIds){
		if(validation.hasErrors()){
			error("参数无效");
		}
		if(roleId != null && !"".equals(menuIds)){
			Role r = Role.findById(roleId);
			if(r != null){
				RoleMenu.delete("role=?", r);
				String[] mIds = menuIds.split(",");
				for(String mId : mIds){
					Symenu m = Symenu.findById(Long.valueOf(mId));	
					if(m!=null && m.parentMenu != null && m.parentMenu!=null 
							&& !RoleMenu.isExist(r, m.parentMenu)){
						new RoleMenu(r,m.parentMenu).save();
					}
					if(!RoleMenu.isExist(r, m)){
						new RoleMenu(r,m).save();
					}
				}
			}
			ok();
		}
		error("无法保存");
	}
	
	public static void allRole(){
		List<Role> roles = Role.findAll();
		String rj = YUtils.ligerGridData(Role.toJson(roles), roles.size());
		renderJSON(rj);
	}

}
